
kb.urls = (function(urls){
  var self = urls;

  var defaultUrl = "http://{host}/Sites/Home/SiteMap?sitename={siteName}";

  self.getDefaultUrl = function(host, siteName){
    return defaultUrl
      .replace("{host}", host)
      .replace("{siteName}", siteName);
  }

  self.buildUrl = function(url, siteName, repository){
    var newQuery = "";

    var params = kb.urls.getQueryParams(url);
    for (var i = 0; i < params.length; i++) {
      var param = params[i];
      if (param.key == "sitename") {
        newQuery += "&" + param.key + "=" + siteName;
      }
      else if (param.key == "repositoryname") {
        newQuery += "&" + param.key + "=" + repository;
      }
      else{
        newQuery += "&" + param.key + "=" + param.value;
      };
    };

    if (newQuery.indexOf('&') == 0) {
      newQuery = newQuery.substring(1);
    };

    return url.substring(0, url.indexOf('?') + 1) + newQuery;
  };

  self.getQueryParams = function(url){
    var query = url.substring(url.indexOf("?") + 1);
    var items = query.split("&");

    var params = [];

    for (var i = 0; i < items.length; i++) {
      var item = items[i];
      var _items = item.split("=");
      if (_items.length == 2) { 
        params.push({
          key: _items[0].toLowerCase(),
          value: _items[1]
        });
      };
    };

    return params;
  };

  self.getQueryParamValue = function(url, key){
    var key = key.toLowerCase();
    var params = self.getQueryParams(url);

    for (var i = 0; i < params.length; i++) {
      if (params[i].key == key) {
        return params[i].value;
      };
    };

    return "";
  };

  return self;
}(kb.urls || {}));

kb.tabs = (function(tabs){
  var self = tabs;

  self.currentTab = null;

  self.getCurrentUrlHost = function(){
    if (self.currentTab) {
      return self.currentTab.url.split("/")[2];
    };

    return "";
  };

  self.getCurrentSiteName = function(){
    var params = kb.urls.getQueryParamValue(kb.tabs.currentTab.url, "siteName");

    return params;
  };

  self.runScript = function(tabId, jsCode){
    chrome.tabs.executeScript(
     tabId,
     {
       code: jsCode
     }
    );
  };

  self.redirect = function(tabId, url){
    self.runScript(tabId, "document.location = '" + url + "'");
    window.close();
  };

  return self;
})(kb.tabs || {});



(function(){

  chrome.tabs.getSelected(null, function(tab) {
    kb.tabs.currentTab = tab;

    bindHosts();
    var currentHost = kb.tabs.getCurrentUrlHost();
    hightlightHost(currentHost);

    bindSites(currentHost);
  });

  function bindHosts(){
    $("#host-list")
    .html("<li></li>")
    .directives({ 
      "li": {
        "Host <- Hosts":{
          ".": "Host",
          "@data-host": "Host",
        }
      }
    })
    .render({Hosts: kb.hosts.all()})
    .find("li")
    .append("<a href=\"#\" class=\"remove\" title=\"remove\"></a>")
    .click(function(){
      var host = $(this).attr("data-host");
      hightlightHost(host);
      bindSites(host);
    })
    .find("a.remove")
    .click(function(){
      var $parent = $(this).parent();
      kb.hosts.remove($parent.attr("data-host"));

      $parent.remove();
      bindSites("");
    });
  };

  function bindSites(host){
    $("#site-list")
    .html("<li></li>")
    .directives({
      "li": {
        "Site <- Sites": {
          ".": "Site.Name",
          "@data-sitename": "Site.Name",
          "@data-repository": "Site.Repository"
        },
        sort: function(a, b){
          return a.Name > b.Name ? 1 : -1;
        }
      }
    })
    .render({Sites: kb.sites.getSites(host)})
    .find("li")
    .click(function(){
      var $this = $(this);
      var siteName = $this.attr("data-sitename");
      var repository = $this.attr("data-repository");

      var url = "";

      if ($("#site-list li.active").length == 0) {
        var host = $("#host-list li.active").attr("data-host");
        url = kb.urls.getDefaultUrl(host, siteName);
      }
      else{
        url = kb.urls.buildUrl(kb.tabs.currentTab.url, siteName, repository);
      };
      
      kb.tabs.redirect(kb.tabs.currentTab.id, url);

      hightlightSite(siteName);
    });

    // hightlight the current site while switching the sites by clicking the host
    if (kb.tabs.getCurrentUrlHost() == host) {
      hightlightSite(kb.tabs.getCurrentSiteName());
    };
  };

  function hightlightHost(host){
    $("#host-list")
    .find(".active")
    .removeClass("active")
    .end()
    .find("li[data-host='" + host + "']")
    .addClass("active");
  };

  function hightlightSite(siteName){
    $("#site-list")
    .find(".active")
    .removeClass("active")
    .end()
    .find("li[data-sitename='" + siteName + "']")
    .addClass("active");
  };

  $(function(){
    $("#clear-all").click(function(){
      if (confirm("Are you sure to delete all the sites?") == false) {
        return;
      };

      kb.hosts.removeAll();
      kb.sites.removeAll();

      bindHosts();
      bindSites("");
    });
  });
})();